<template>
  <div class="modal">
    <el-dialog
      v-model="modalState"
      :title="isNewRef ? modalConfig.header.newTitle : modalConfig.header.editTitle"
      width="30%"
      center
    >
      <div class="form">
        <el-form
          :model="formData"
          label-width="100px"
          label-position="left"
          size="large"
          ref="ruleFormRef"
          :rules="rules"
          status-icon
        >
          <template v-for="item in modalConfig.formItem" :key="item.prop">
            <template v-if="isNewRef">
              <el-form-item :prop="item.prop" :label="item.label" clearable>
                <template v-if="item.type === 'input'">
                  <el-input v-model="formData[item.prop]" :placeholder="item.placeholder" />
                </template>

                <template v-if="item.type === 'date-picker'">
                  <el-date-picker
                    type="daterange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    v-model="formData[item.prop]"
                  />
                </template>

                <template v-if="item.type === 'select'">
                  <el-select v-bind="item" style="width: 100%" v-model="formData[item.prop]">
                    <template v-for="option in item.options" :key="option.value">
                      <el-option :label="option.label" :value="option.value" />
                    </template>
                  </el-select>
                </template>

                <template v-if="item.type === 'custom'">
                  <slot :name="item.soltName"></slot>
                </template>
              </el-form-item>
            </template>

            <template v-if="!isNewRef && !item.editHaddle">
              <el-form-item :prop="item.prop" :label="item.label" clearable>
                <template v-if="item.type === 'input'">
                  <el-input v-model="formData[item.prop]" :placeholder="item.placeholder" />
                </template>

                <template v-if="item.type === 'date-picker'">
                  <el-date-picker
                    type="daterange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    v-model="formData[item.prop]"
                  />
                </template>

                <template v-if="item.type === 'select'">
                  <el-select v-bind="item" style="width: 100%" v-model="formData[item.prop]">
                    <template v-for="option in item.options" :key="option.value">
                      <el-option :label="option.label" :value="option.value" />
                    </template>
                  </el-select>
                </template>

                <template v-if="item.type === 'custom'">
                  <slot :name="item.soltName"></slot>
                </template>
              </el-form-item>
            </template>
          </template>
        </el-form>
      </div>

      <template #footer>
        <div class="btns">
          <el-button type="primary" @click="handleConfirmClick">提交</el-button>
          <el-button @click="modalState = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineExpose, reactive, defineProps } from 'vue'
import { ElMessage } from 'element-plus'

import useStytem from '@/store/main/system/system'
import useMainStore from '@/store/main/main'

import type { FormRules, FormInstance } from 'element-plus'

interface IProps {
  modalConfig: {
    pageName: string
    header: {
      newTitle: string
      editTitle: string
    }
    formItem: any[]
  }
  otherInfo?: any
}

const props = defineProps<IProps>()
const mainStore = useMainStore()
const systemStore = useStytem()
const modalState = ref(false)
const ruleFormRef = ref<FormInstance>()

const initialData: any = {}
for (const item of props.modalConfig.formItem) {
  initialData[item.prop] = ''
}

console.log(props.otherInfo)

const formData = reactive(initialData)
// 判断是否是点击新建按钮弹出弹窗
const isNewRef = ref()
const editData = ref()

// 表单校验规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      max: 20,
      message: '必须由4~20位数字或字母组成',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      min: 4,
      message: '密码长度至少为4位',
      trigger: 'blur'
    },
    {
      message: '密码必须包含大小写字母和数字的组合',
      trigger: 'blur',
      pattern: /^[a-z0-9A-Z]{4,}$/
    }
  ],
  realname: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      message: '请输入2位以上的汉字',
      trigger: 'blur',
      pattern: /^[\u4e00-\u9fa5]{0,}$/
    }
  ],
  cellphone: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      message: '请输入正确格式的手机号码',
      trigger: 'blur',
      pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
    }
  ]
}

function setModalState(isNew: boolean = true, itemData?: any) {
  modalState.value = true
  isNewRef.value = isNew
  editData.value = itemData
  if (!isNew && formData) {
    // 新建用户
    for (const key in formData) {
      formData[key] = itemData[key]
    }
  } else {
    // 修改用户
    for (const key in formData) {
      formData[key] = ''
    }
  }
}

// 提交按钮的事件
function handleConfirmClick() {
  let infoData = formData
  if (props.otherInfo) {
    infoData = { ...infoData, ...props.otherInfo }
  }
  ruleFormRef.value.validate(async (value) => {
    if (value) {
      if (isNewRef.value) {
        // 新建用户
        systemStore.createPageDataListAction(props.modalConfig.pageName, infoData).then((res) => {
          if (res.code === 0) {
            ElMessage({
              message: '用户创建成功',
              type: 'success'
            })
          } else {
            ElMessage({
              message: '用户创建失败',
              type: 'error'
            })
          }
        })
      } else {
        // 修改用户
        systemStore
          .editPageDataListAction(props.modalConfig.pageName, editData.value.id, infoData)
          .then((res) => {
            if (res.code === 0) {
              ElMessage({
                message: '修改成功',
                type: 'success'
              })
            } else {
              ElMessage({
                message: '修改失败',
                type: 'error'
              })
            }
          })
      }

      modalState.value = false
      ruleFormRef.value.resetFields()
    } else {
      ElMessage({
        message: '检验不通过,请重试',
        type: 'warning'
      })
    }
  })
}

defineExpose({ setModalState })
</script>

<style lang="scss" scoped>
.btns {
  display: flex;
  justify-content: flex-end;
}
</style>
